# Generated by Django 2.2.9 on 2020-03-04 10:30

from django.contrib.auth import get_user_model
from django.db import migrations
from rolepermissions.checkers import has_role
from rolepermissions.permissions import revoke_permission
from rolepermissions.roles import assign_role


def reset_power_and_state_roles(apps, schema_editor):
    User = get_user_model()
    for user in User.objects.all():
        # Re-assigning the roles will sync the default associated permissions
        for role in ["state_manager", "power_user"]:
            if has_role(user, role):
                assign_role(user, role)


def revoke_user_permissions_for_invoices(apps, schema_editor):
    User = get_user_model()
    for user in User.objects.all():
        for perm in ["challenge_invoice_cru", "challenge_invoice_reset_to_draft"]:
            for role in ["state_manager", "power_user"]:
                if has_role(user, role):
                    revoke_permission(user, perm)
        user.save()


class Migration(migrations.Migration):
    dependencies = [
        ("challenge", "0055_annualstatesetting_historicalannualstatesetting"),
    ]

    operations = [
        migrations.RunPython(
            reset_power_and_state_roles, revoke_user_permissions_for_invoices
        ),
    ]
